//
//  LevelScene.m
//  MessangerSkeleton
//
//  Created by User-23 on 4/17/14.
//  Copyright (c) 2014 IOTrainingCamp. All rights reserved.
//

#import "LevelScene.h"
#import "GamePlay.h"
#import "NetworkManager.h"

#import "GameScene.h"
#import "IntroScene.h"

#import "Configuration.h"

@interface LevelScene ()

@property(nonatomic) GamePlay *gamePlay;
@property(nonatomic) NetworkManager *networkManager;

@property(nonatomic) id canceledOpponentObserver;
@property(nonatomic) id connectedPeerObserver;
@property(nonatomic) id disconnectedOpponentObserver;
@property(nonatomic) id receivedDataObserver;
@property(nonatomic) id playerChoosingCharacterObserver;
@property(nonatomic) id playerWaitingForEnemyForChoosingCharacterObserver;
@property(nonatomic) id opponentIsReadyToStartObserver;
@property(nonatomic) id playerIsReadyToStartObserver;

@property(nonatomic) BOOL isCharacterChoosen;
@property(nonatomic) BOOL isPlayerReadyToStart;
@property(nonatomic) BOOL isOpponentReadyToStart;

@end

@implementation LevelScene

#define kTextForButtonForFindingAnOpponent @"[ Find an opponent ]"
#define kTextForButtonMenu @"[ Menu ]"

#define kNameButtonForFindingAnOpponent @"findAnOpponentButton"
#define kNameRoute @"route"
#define kNamePlayer @"player"
#define kNameEnemy @"enemy"

#define kLevelOneButtonName @"[ Level One ]"

#define kGoodCharacterButtonName @"GoodCharacter"
#define kBadCharacterButtonName @"BadCharacter"

#define kStartNameButtonName @"StartMultiplayerGame"

// -----------------------------------------------------------------------
#pragma mark - Create & Destroy
// -----------------------------------------------------------------------

+ (LevelScene *)scene
{
	return [[self alloc] init];
}

// -----------------------------------------------------------------------

- (id)init
{
    // Apple recommend assigning self with supers return value
    self = [super init];
    if (!self) return(nil);
    
    self.gamePlay = [GamePlay sharedInstance];
    
    // Create a colored background (Dark Grey)
    CCNodeColor *background = [CCNodeColor nodeWithColor:[CCColor colorWithRed:0.2f green:0.2f blue:0.2f alpha:1.0f]];
    [self addChild:background];
    
    NSLog(@"self.gamePlay.gameState = %d", self.gamePlay.gameState);
    
    //TODO - update levels
    if ( self.gamePlay.gameState == kGameStateLaunchedSinglePlayer )
    {
        [self showButtonsForLevels];
    
    }else if ( self.gamePlay.gameState == kGameStateLaunchedMultiPlayer )
    {
        //NetworkManager -singleton?
        NSLog(@"multiplayer");

        
//        //look for an opponent
//        CCButton *findAnOpponentButton = [CCButton buttonWithTitle:kTextForButtonForFindingAnOpponent fontName:@"Verdana-Bold" fontSize:18.0f];
//        findAnOpponentButton.positionType = CCPositionTypeNormalized;
//        findAnOpponentButton.position = ccp(0.5f, 0.2f); // Top Right of screen
//        [findAnOpponentButton setTarget:self selector:@selector(startLookingForOponent)];
//        findAnOpponentButton.name = kNameButtonForFindingAnOpponent;
//        [self addChild:findAnOpponentButton];
        
        [self addObserversToScene];
        
        self.networkManager = [NetworkManager sharedInstance];
        [self.networkManager startLookingForOponent];
        
    }
    
    // Create a back button
    CCButton *backButton = [CCButton buttonWithTitle:kTextForButtonMenu fontName:@"Verdana-Bold" fontSize:18.0f];
    backButton.positionType = CCPositionTypeNormalized;
    backButton.position = ccp(0.85f, 0.95f); // Top Right of screen
    [backButton setTarget:self selector:@selector(onBackClicked:)];
    [self addChild:backButton];

    
    // done
	return self;
}

// -----------------------------------------------------------------------
#pragma mark - Button Callbacks
// -----------------------------------------------------------------------

- (void)onBackClicked:(id)sender
{
    // back to intro scene with transition
    [[CCDirector sharedDirector] replaceScene:[IntroScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionRight duration:1.0f]];
}

- (void)playLevel:(id)sender
{
   
    
    if ( [sender isKindOfClass:[CCButton class]] ){
        CCButton *pressedButton = sender;
        
        if ( [pressedButton.name isEqualToString:kLevelOneButtonName] )
        {
            
            //TODO - set current Level/format?
            self.gamePlay.level = 1;
            if ( self.gamePlay.gameState == kGameStateLaunchedSinglePlayer ){
                [[CCDirector sharedDirector] replaceScene:[GameScene scene]
                                       withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionLeft duration:1.0f]];
            }
        }
    }
}

- (void)removeObserversFromScene
{
    [[NSNotificationCenter defaultCenter] removeObserver:self.canceledOpponentObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.connectedPeerObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.disconnectedOpponentObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.receivedDataObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.playerChoosingCharacterObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.opponentIsReadyToStartObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.playerIsReadyToStartObserver];
    [[NSNotificationCenter defaultCenter] removeObserver:self.playerWaitingForEnemyForChoosingCharacterObserver];
    
    NSLog(@"Observers are removed");
}

- (void)addObserversToScene
{
    NSLog(@"Observers are added");
    
    self.canceledOpponentObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNameForCanceledLookingForAnOpponent object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        //TODO - seening the button for finding an opponent
        //only for testing purposes
        NSLog(@"pressed cancel - notification block");
        [[CCDirector sharedDirector] replaceScene:[IntroScene scene]
                                   withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionRight duration:1.0f]];
        
    }];
    
    self.connectedPeerObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNameForConnectedPeer object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        
        NSLog(@"connected to peer - notification block");
    }];
    
    self.disconnectedOpponentObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNameForDisconnectedOpponent object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"peer is disconnected - notification block");
    }];
    
    self.receivedDataObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNameForReceivedData object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"received data - notification block");
    }];
    
    self.playerChoosingCharacterObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNamePlayerChoosingCharacter object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"playerChoosingCharacterObserver - notification block");
        [self showButtonsForLevels];
        [self showButtonsForChoosingACharacter];
        [self showButtonForStartingGame];

    }];
    
    self.opponentIsReadyToStartObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNameOpponentIsReadyToStart object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"opponentIsReadyToStartObserver - notification block");
        
        self.isOpponentReadyToStart = YES;
        [self playGameIfBothAreReady];
    }];
    
    self.playerIsReadyToStartObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNamePlayerIsReadyToStart object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"opponentIsReadyToStartObserver - notification block");
        self.isPlayerReadyToStart = YES;
        [self.networkManager sendThatThePlayerIsReadyToPlay];
        [self playGameIfBothAreReady];
    }];

    
    
    
    self.playerWaitingForEnemyForChoosingCharacterObserver = [[NSNotificationCenter defaultCenter] addObserverForName:kNetworkNotificationNamePlayerWaitingForEnemyForChoosingCharacter object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
        NSLog(@"playerWaitingForEnemyForChoosingCharacterObserver - notification block");
    }];
}

//TODO - implement Button for looking for an opponent
- (void)startLookingForOponent
{
}

- (void)playGameIfBothAreReady
{
    if ( self.isPlayerReadyToStart && self.isOpponentReadyToStart ) {
        [[CCDirector sharedDirector] replaceScene:[GameScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionLeft duration:1.0f]];
    }
}
- (void)showButtonsForChoosingACharacter
{
    CCButton *goodCharacterButton = [CCButton buttonWithTitle:@"[ the good one ]" fontName:@"Verdana-Bold" fontSize:18.0f];
    goodCharacterButton.positionType = CCPositionTypeNormalized;
    goodCharacterButton.position = ccp(0.2f, 0.7f);
    goodCharacterButton.name = kGoodCharacterButtonName;
    [goodCharacterButton setTarget:self selector:@selector(chooseCharacter:)];
    [self addChild:goodCharacterButton];
    
    CCButton *badCharacterButton = [CCButton buttonWithTitle:@"[ the bad one ]" fontName:@"Verdana-Bold" fontSize:18.0f];
    badCharacterButton.positionType = CCPositionTypeNormalized;
    badCharacterButton.position = ccp(0.2f, 0.3f);
    badCharacterButton.name = kBadCharacterButtonName;
    [badCharacterButton setTarget:self selector:@selector(chooseCharacter:)];
    [self addChild:badCharacterButton];
    
    
}

- (void)showButtonForStartingGame
{
    CCButton *startGameButton = [CCButton buttonWithTitle:@"[ lets play! ]" fontName:@"Verdana-Bold" fontSize:18.0f];
    startGameButton.positionType = CCPositionTypeNormalized;
    startGameButton.position = ccp(0.7f, 0.3f);
    startGameButton.name = kStartNameButtonName;
    [startGameButton setTarget:self selector:@selector(startGame)];
    [self addChild:startGameButton];
}


- (void)startGame
{
    if ( self.isCharacterChoosen && self.gamePlay.level>0  )
    {
        [self.networkManager sendToOpponentLevel:self.gamePlay.level andCharacterType:[self getCharacterForTheOpponent]];
        [self.networkManager sendThatThePlayerIsReadyToPlay];
        self.isPlayerReadyToStart = YES;
        [self playGameIfBothAreReady];
    }
}

- (void)chooseCharacter:(id)sender
{
    if ( [sender isKindOfClass:[CCButton class]] ){
        CCButton *pressedButton = sender;
        
        
        if ( [pressedButton.name isEqualToString:kGoodCharacterButtonName] )
        {
            self.gamePlay.characterType = kMessengerSelf;
            self.isCharacterChoosen = YES;
        
        }else if  ( [pressedButton.name isEqualToString:kBadCharacterButtonName] )
        {
            self.gamePlay.characterType = kMessengerEnemy;
            self.isCharacterChoosen = YES;
        }
    }
}

- (MessengerSpriteType)getCharacterForTheOpponent
{
    if (self.gamePlay.characterType == kMessengerSelf ) {
        return kMessengerEnemy;
    }
    return kMessengerSelf;
}
// -----------------------------------------------------------------------

//- (void)showButtonsForLevels:(NSArray *)activeLevels
- (void)showButtonsForLevels
{
    CCButton *levelOneButton = [CCButton buttonWithTitle:@"[ level one ]" fontName:@"Verdana-Bold" fontSize:18.0f];
    levelOneButton.positionType = CCPositionTypeNormalized;
    levelOneButton.position = ccp(0.5f, 0.5f);
    levelOneButton.name = kLevelOneButtonName;
    [levelOneButton setTarget:self selector:@selector(playLevel:)];
    [self addChild:levelOneButton];
}


- (void)showButtonForOpponent
{
    //look for an opponent
    CCButton *findAnOpponentButton = [CCButton buttonWithTitle:kTextForButtonForFindingAnOpponent fontName:@"Verdana-Bold" fontSize:18.0f];
    findAnOpponentButton.positionType = CCPositionTypeNormalized;
    findAnOpponentButton.position = ccp(0.5f, 0.2f);
    [findAnOpponentButton setTarget:self selector:@selector(startLookingForOponent)];
    findAnOpponentButton.name = kNameButtonForFindingAnOpponent;
    [self addChild:findAnOpponentButton];
}


-(void)dealloc
{
    [self removeObserversFromScene];
}
@end
